package views;

import DTO.ConstantesDTO;
import DTO.UsuarioDTO;
import Servicios.ServiciosFactory;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import controllers.LoginControl;

/**
 * Dialogo que implementa la interfaz de login
 * @author eagle_eye
 */
public class LoginDialog extends JDialog {

    private JTextField tfname;
    private JPasswordField ptfPasswd;
    private JButton btnCancelar;
    private JButton btnAceptar;
    private LoginControl loginControl;

    public LoginDialog() {

        super((java.awt.Dialog) null, true);
        this.setLocationRelativeTo(null);
        this.setAlwaysOnTop(true);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Inicio Sesión");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);
        JPanel container = new JPanel();
        container.setLayout(new BorderLayout());
        container.setBackground(new java.awt.Color(255, 255, 255));
        JPanel vista = builVistaPanel();
        container.setBorder(new LineBorder(Color.gray));
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setBackground(new java.awt.Color(255, 255, 255));
        btnCancelar = new JButton();
        btnCancelar.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                CancelPressed();
            }
        });

        btnAceptar = new JButton();
        btnAceptar.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                OKPressed(e);
            }
        });

        btnAceptar.setFont(new java.awt.Font("Tahoma", 0, 14));
        btnAceptar.setIcon(new javax.swing.ImageIcon("resources/accept.png"));
        btnAceptar.setText("Aceptar");

        btnCancelar.setFont(new java.awt.Font("Tahoma", 0, 14));
        btnCancelar.setIcon(new javax.swing.ImageIcon("resources/reject.png"));
        btnCancelar.setText("Cancelar");

        buttonPanel.add(btnCancelar);
        buttonPanel.add(btnAceptar);
        getRootPane().setDefaultButton(btnAceptar);
        container.add(vista, BorderLayout.CENTER);
        container.add(buttonPanel, BorderLayout.SOUTH);

        getContentPane().add(container);
        pack();
        centerDialog();
        UIManager.addPropertyChangeListener(new UISwitchListener(container));
    }

    /**
     * Metodo que maneja el evento del textFile de la clave.
     * @param evt
     */
    private void jPasswordFieldPasswordActionPerformed(java.awt.event.ActionEvent evt) {
        OKPressed(evt);
    }

    /**
     * Metodo que construye el panel central del Dialog Login
     * @return Jpanel
     */
    public JPanel builVistaPanel() {
        JPanel vista;
        JLabel lblBienBenida = new JLabel();
        JLabel lblImage = new JLabel();
        JLabel lblNombre = new JLabel("Nombre: ", JLabel.RIGHT);
        JLabel lblPaswd = new JLabel("Contarseña: ", JLabel.RIGHT);
        tfname = new JTextField(20);
        ptfPasswd = new JPasswordField(20);

        lblBienBenida.setFont(new java.awt.Font("Ouhod-Bold", 1, 18));
        lblBienBenida.setForeground(new java.awt.Color(0, 0, 0));
        lblBienBenida.setText(" Mi Colegio");

        ptfPasswd.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordFieldPasswordActionPerformed(evt);
            }
        });

        vista = new JPanel();
        this.setResizable(false);
        vista.setBackground(new java.awt.Color(255, 255, 255));
        lblImage.setIcon(new javax.swing.ImageIcon("resources/escudo.png"));


        GroupLayout layout = new GroupLayout(vista);
        layout.setAutoCreateGaps(false);
        layout.setAutoCreateContainerGaps(true);
        vista.setLayout(layout);

        layout.setHorizontalGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup()
                .addComponent(lblImage).addComponent(lblBienBenida,
                javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
                .addGap(60, 60, 60).addGroup(layout.createParallelGroup()
                .addComponent(lblBienBenida)).addComponent(lblNombre)
                .addComponent(lblPaswd)).addGroup(layout.createParallelGroup()
                .addComponent(tfname).addComponent(ptfPasswd)));
        layout.setVerticalGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup().addComponent(lblImage))
                .addGroup(layout.createParallelGroup().addComponent(lblBienBenida,
                javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing
                .GroupLayout.PREFERRED_SIZE)).addGap(60, 60, 60)
                .addGroup(layout.createParallelGroup().addComponent(lblBienBenida)
                .addComponent(lblNombre).addComponent(tfname))
                .addGroup(layout.createParallelGroup()
                .addComponent(lblPaswd).addComponent(ptfPasswd)));

        return vista;
    }

    protected void centerDialog() {
        Dimension screenSize = this.getToolkit().getScreenSize();
        Dimension size = this.getSize();
        screenSize.height = screenSize.height / 2;
        screenSize.width = screenSize.width / 2;
        size.height = size.height / 2;
        size.width = size.width / 2;
        int y = screenSize.height - size.height;
        int x = screenSize.width - size.width;
        this.setLocation(x, y);
    }

    public void CancelPressed() {
        System.exit(0);
    }

    /**
     * Evento del boton aceptar
     */
    public void OKPressed(java.awt.event.ActionEvent evt) {
        UsuarioDTO usuario = readUser();
        try {
            loginControl = new LoginControl();
            int validate = ConstantesDTO.VALIDATE_DEFAULT;
            validate = loginControl.validate(usuario);
            switch (validate) {
                case ConstantesDTO.FORMATO_NOMBRE_INCORRECTO: {
                    JOptionPane.showMessageDialog(this, "El formato del nombre es incorrecto");
                    ptfPasswd.setText("");
                    tfname.setText("");
                    break;
                }
                case ConstantesDTO.FORMATO_CONTRASENA_INCORRECTO: {
                    JOptionPane.showMessageDialog(this, "El formato de la contraseña es incorrecto.\nLongitud entre 5 y 30 caracteres, inclusive."
                            + "\nDebe contener por lo menos:\n* Un número, una letra minúscula, una letra mayúscula.\nEj: Mysecret1.");
                    ptfPasswd.setText("");
                    tfname.setText("");
                    break;
                }
                case ConstantesDTO.LONGITUD_NOMBRE_INCORRECTO: {
                    JOptionPane.showMessageDialog(this, "La longitud del nombre es incorrecto");
                    break;
                }
                case ConstantesDTO.LONGITUD_CONTRASENA_INCORRECTO: {
                    JOptionPane.showMessageDialog(this, "La longitud de la contraseña es incorreta");
                    ptfPasswd.setText("");
                    break;
                }
                case ConstantesDTO.LOGIN_EXITOSO: {

                    if (!usuario.getPassword().equals(ServiciosFactory.getLoginServicio().getUsuarioDTO().getPassword())) {
                        JOptionPane.showMessageDialog(this, "Password o Usuario errados");
                        ptfPasswd.setText("");
                        tfname.setText("");
                    } else {
                        doLogin();
                    }
                    break;
                }
                case ConstantesDTO.USUARIO_INEXISTENTE: {
                    JDialog.setDefaultLookAndFeelDecorated(true);
                    JOptionPane.showMessageDialog(this, "User y pass bien, pero usuario no existe");
                    break;
                }
            }
        } catch (Exception exception) {
            JOptionPane.showMessageDialog(null, "Error de conexion.");
            System.out.println("Error de conexion: " + exception.getMessage());
        }

    }

    /**
     * Metodo que controla el nivel de acceso de los Usuarios del sistema.
     */
    public void doLogin() {
        System.out.println("ID: " + ServiciosFactory.getLoginServicio().getUsuarioDTO().getTipousuario());
        PrincipalFrame principal = new PrincipalFrame();
        if (ServiciosFactory.getLoginServicio().getUsuarioDTO().getTipousuario() == 2) {
            principal.getAulas().setVisible(false);
            principal.getAreas().setVisible(false);
            principal.getAulas().setVisible(false);
            principal.getDocumentos().setVisible(false);
            principal.getUsuarios().setVisible(false);
            this.setVisible(false);
            this.dispose();
            principal.setVisible(true);
            JOptionPane.showMessageDialog(principal, "Bienvenido "
                    + ServiciosFactory.getLoginServicio().getUsuarioDTO().getUsuario()
                    + "\nRol: profesor.");
        } else if (ServiciosFactory.getLoginServicio().getUsuarioDTO().getTipousuario() == 3) {
            principal.getAulas().setVisible(false);
            principal.getAreas().setVisible(false);
            principal.getAulas().setVisible(false);
            principal.getProfesores().setVisible(false);
            principal.getUsuarios().setVisible(false);
            principal.getCursos().setVisible(false);
            this.setVisible(false);
            this.dispose();
            principal.setVisible(true);
            JOptionPane.showMessageDialog(principal, "Bienvenido "
                    + ServiciosFactory.getLoginServicio().getUsuarioDTO().getUsuario()
                    + "\nRol: estudiante.");

        } else {
            this.setVisible(false);
            this.dispose();
            principal.setVisible(true);
            JOptionPane.showMessageDialog(principal, "Bienvenido "
                    + ServiciosFactory.getLoginServicio().getUsuarioDTO().getUsuario()
                    + "\nRol: administrador.");
        }
    }

    /**
     * Metodo que obtieene el user y passwd del usuario.
     * @return  {@link UsuaarioDTO}
     */
    public UsuarioDTO readUser() {
        String user = "Rvillabonas1" ;//tfname.getText();
        //char[] passArray = ptfPasswd.getPassword();
        String pass = "Rvillabonas1";//new String(passArray);
        return new UsuarioDTO(user, pass);
    }
}

class ColumnLayout implements LayoutManager {

    int xInset = 80;
    int yInset = 80;
    int yGap = 32;

    public void addLayoutComponent(String s, Component c) {
    }

    public void layoutContainer(Container c) {
        Insets insets = c.getInsets();
        int height = yInset + insets.top;

        Component[] children = c.getComponents();
        Dimension compSize = null;
        for (int i = 0; i < children.length; i++) {
            compSize = children[i].getPreferredSize();
            children[i].setSize(compSize.width, compSize.height);
            children[i].setLocation(xInset + insets.left, height);
            height += compSize.height + yGap;
        }

    }

    public Dimension minimumLayoutSize(Container c) {
        Insets insets = c.getInsets();
        int height = yInset + insets.top;
        int width = 0 + insets.left + insets.right;

        Component[] children = c.getComponents();
        Dimension compSize = null;
        for (int i = 0; i < children.length; i++) {
            compSize = children[i].getPreferredSize();
            height += compSize.height + yGap;
            width = Math.max(width, compSize.width + insets.left + insets.right + xInset * 2);
        }
        height += insets.bottom;
        return new Dimension(width, height);
    }

    public Dimension preferredLayoutSize(Container c) {
        return minimumLayoutSize(c);
    }

    public void removeLayoutComponent(Component c) {
    }
}
